import React, { Component } from 'react';
import store from '../../redux/store';
import {createDecrementAction,createIncrementAction,createAsyncIncrementAction} from '../../redux/count_action'

export default class Count extends Component {

    // 由于redux只负责管理状态，并不会主动刷新页面，所以这里的话需要我们手动给组件绑定状态订阅
    componentDidMount(){
        store.subscribe(()=>{
            this.setState({})
        })
    }
    // 有了actionCreator ， 我们就不需要自己再去定义action了
    increment = () => {
        const { value } = this.countNum;
        store.dispatch(createIncrementAction(value*1));
    }

    decrement = () => {
        const { value } = this.countNum;
        store.dispatch(createDecrementAction(value*1));
    }

    incrementIfOdd = () => {
        const { value } = this.countNum;
        if(store.getState() % 2 === 1){
            store.dispatch(createIncrementAction(value*1));
        }
    }


    incrementAsync = () => {
        const { value } = this.countNum;
        store.dispatch(createAsyncIncrementAction(value*1,500));
    }

    render() {
        return (
            <div>
                <h2>总数为： {store.getState()}</h2>
                <select ref={a => this.countNum = a}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>&nbsp;
                <button onClick={this.increment}>+</button>&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;
                <button onClick={this.incrementIfOdd}>add if odd</button>&nbsp;
                <button onClick={this.incrementAsync}>add async</button>&nbsp;
            </div>
        )
    }
}